package mware_lib;

public class ObjectBroker {
    private Communication communication;
    private ObjectReferences objectReferences = new ObjectReferences();
    private ObjectBrokerDeamon objectBrokerDeamon;

    public ObjectBroker(String serviceName, int port) {
        communication = new Communication(serviceName, port);

        objectBrokerDeamon = new ObjectBrokerDeamon(objectReferences, port);
        objectBrokerDeamon.start();
    }

    /**
     * Initializes the ObjectBroker / creates the local NameService
     *
     * @param serviceName hostname or IP of Nameservice
     * @param port        port NameService is listening at
     * @return an ObjectBroker Interface to Nameservice
     */
    public static ObjectBroker init(String serviceName, int port) {
        if (Config.DEBUGGER) System.out.println("Objectbroker  init");
        return new ObjectBroker(serviceName, port);
    }

    /**
     * @return an Implementation for a local NameService
     */
    public NameService getNameService() {
        if (Config.DEBUGGER) System.out.println("Objectbroker  getNameService");
        return new NameServiceImpl(objectReferences, communication);
    }

    /**
     * shuts down the process, the OjectBroker is running in
     * terminates process
     */
    public void shutDown() {
        objectBrokerDeamon.interrupt();
        objectBrokerDeamon.shutDown();
        communication = null;
        objectReferences = null;
        if (Config.DEBUGGER) System.out.println("OBJECTBROKER shutDown");
    }
}
